﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Home.Haushalt.Lib;
using Home.Haushalt.Lib.Element;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Collections.Specialized;
using System.Linq;


namespace Home.Haushalt.Gui
{
    /// <summary>
    /// 
    /// </summary>
    public partial class UcGridFormDocument : UcGridForm
    {
        /// <summary> </summary>
        private List<int> _parentDocumentIDs = new List<int>();

        /// <summary></summary>
        private OpenFileDialog _openFileDialog = new OpenFileDialog();

        /// <summary>
        /// 
        /// </summary>
        public UcGridFormDocument()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="columnSet"></param>
        /// <param name="layoutName"></param>
        public UcGridFormDocument(DefaultColumnSets columnSet, string layoutName)
            : base(columnSet, layoutName)
        {
            InitializeComponent();

            gridPage.OnLayoutChanged += new EventHandler<HEventArgs>(grid_OnStatusMessage);
            gridPage.OnStatusMessage += new EventHandler<HEventArgs>(grid_OnStatusMessage);
            gridPage.DoubleClickRow += new DoubleClickRowEventHandler(gridPage_DoubleClickRow);
            gridPage.DragEnter += new System.Windows.Forms.DragEventHandler(gridPage_DragEnter);
            gridPage.DragDrop += new DragEventHandler(gridPage_DragDrop);
            gridPage.ContextMenuStrip.Opened += new EventHandler(ContextMenuStrip_Opened);

            gridPage.DisplayLayout.Override.AllowDelete = DefaultableBoolean.False;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmGridForm_Load(object sender, EventArgs e)
        {
            if (!LayoutController.IsInDesignMode(this))
            {
                DataBind();
            }
        }

        #region PAGE GRID

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ContextMenuStrip_Opened(object sender, EventArgs e)
        {
            if (gridPage._clickedObject is UltraGridCell || gridPage._clickedObject is UltraGrid)
            {
                gridPage.ContextMenuStrip.Items.Clear();

                int insertIndex = 0;

                string elementCaption = (gridPage.Selected.Rows.Count > 1) ? LO.ElementList(Page.ElementType) : LO.ElementName(Page.ElementType);

                ToolStripMenuItem openElementItem = new ToolStripMenuItem(LO.GridContextMenu("Element.Open", elementCaption) + " [Enter]", null, cmnuPropertyOpen_Click);
                gridPage.ContextMenuStrip.Items.Insert(insertIndex++, openElementItem);

                ToolStripMenuItem toClipboardElementItem = new ToolStripMenuItem(LO.GridContextMenu("Element.ToClipboard", elementCaption) + " [Strg+C]", null, cmnuCopyToClipboard_Click);
                toClipboardElementItem.Enabled = (gridPage.Selected.Rows.Count > 0);
                gridPage.ContextMenuStrip.Items.Insert(insertIndex++, toClipboardElementItem);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridPage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control)
            {
                switch (e.KeyCode)
                {
                    case Keys.C:
                        cmnuCopyToClipboard_Click(sender, null);
                        break;
                }
            }
            else
            {
                if (e.KeyCode.Equals(Keys.Enter))
                {
                    cmnuPropertyOpen_Click(sender, e);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuCopyToClipboard_Click(object sender, EventArgs e)
        {
            Clipboard.Clear();

            StringCollection paths = new StringCollection();
            foreach (UltraGridRow row in gridPage.Selected.Rows)
            {
                paths.Add(new Page(row.ToDataRow()).DecryptFilePath);
            }

            Clipboard.SetFileDropList(paths);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridPage_DoubleClickRow(object sender, DoubleClickRowEventArgs e)
        {
            cmnuPropertyOpen_Click(sender, e);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuPropertyOpen_Click(object sender, EventArgs e)
        {
            foreach (UltraGridRow row in gridPage.Selected.Rows)
            {
                Page pageObj = new Page(row.ToDataRow());

                string filename = "";

                if (pageObj.Row[Page.Fields.SourceFileName] != null &&
                    pageObj.Row[Page.Fields.SourceFileName].ToString().Length > 0 &&
                    File.Exists(pageObj.Row[Page.Fields.SourceFileName].ToString()))
                {
                    filename = row.ToDataRow()[Page.Fields.SourceFileName].ToString();
                }
                else
                {
                    filename = pageObj.DecryptFilePath;
                }

                try
                {
                    Process.Start(filename);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Datei kann nicht geöffnet werden: " + ex.Message);
                    Journal.Add(this, ex);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridPage_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Bitmap) || e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="documents"></param>
        public void PageDataBind(List<Document> documents)
        {
            if (gridPage.DataSource == null)
            {
                gridPage.DataBind(Page.ElementType, DefaultColumnSets.GridDefault);

                gridPage.LoadLayout(DefaultColumnSets.GridDefault.ToString());

                gridPage.DisplayLayout.Override.AllowRowFiltering = DefaultableBoolean.False;
                gridPage.DisplayLayout.Override.HeaderClickAction = HeaderClickAction.Select;
                gridPage.DisplayLayout.GroupByBox.Hidden = true;

                gridPage.DisplayLayout.Bands[0].SortedColumns.Add(Page.Fields.Index, false);

                // this.DisplayLayout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            }

            ColumnFilter docuIdFilter = gridPage.DisplayLayout.Bands[0].ColumnFilters[Page.Fields.DocumentId];

            docuIdFilter.FilterConditions.Clear();
            docuIdFilter.LogicalOperator = FilterLogicalOperator.Or;

            if (documents.Count > 0)
            {
                foreach (Document document in documents)
                {
                    docuIdFilter.FilterConditions.Add(new FilterCondition(FilterComparisionOperator.Equals, document.ID));
                }
            }
            else
            {
                docuIdFilter.FilterConditions.Add(new FilterCondition(FilterComparisionOperator.Equals, -2));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridPage_DragDrop(object sender, DragEventArgs e)
        {
            if (BaseGrid.Selected.Rows.Count == 1)
            {
                FrmPropertyDocument frmPropertyDocument = (FrmPropertyDocument)BaseGrid.EditElementProperty(BaseGrid.Selected.Rows[0].ToDataRow());
                frmPropertyDocument.AddPages((string[])e.Data.GetData(DataFormats.FileDrop));
            }
        }

        #endregion PAGE GRID


        /// <summary>
        /// 
        /// </summary>
        public override void DataBind()
        {
            BaseGrid.DataBind(Document.ElementType, ColumnSet);

            PageDataBind(new List<Document>());

            //Erst nach dem Page, sonst wird Form-Caption vom page-layout überschrieben
            BaseGrid.LoadLayout(LayoutName);

            grid_AfterSelectChange(null, null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
        {
            List<Document> documents = new List<Document>();
            foreach (UltraGridRow gridRow in BaseGrid.Selected.Rows)
            {
                documents.Add((Document)ElementBase.Instantiate(gridRow.ToDataRow()));
            }

            PageDataBind(documents);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BaseGrid_DragDrop(object sender, DragEventArgs e)
        {
            FrmPropertyDocument frmPropertyDocument = (FrmPropertyDocument)BaseGrid.OnPropertyNewClick();

            frmPropertyDocument.AddPages((string[])e.Data.GetData(DataFormats.FileDrop));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridPage_OnPagesAdded(object sender, HEventArgs e)
        {
            //Wegen Farben
            gridPage.InitializeRowsAppearances();
            WindowController.RefreshGrids(Page.ElementType);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BaseGrid_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Bitmap) || e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BaseGrid_DoubleClickRow(object sender, DoubleClickRowEventArgs e)
        {
            if (BaseGrid.Selected.Rows.Count > 0)
            {
                BaseGrid.EditElementProperty(BaseGrid.Selected.Rows[0].ToDataRow());
            }
        }


    }
}
